/**
 * hxz 共用库
 * Created by dxy on 15/6/24.
 */
define(["jquery", "underscore", "hxzValid", "hxzRest", "alertify", "hxzUI", "select2"], function ($, _, valid, hxzRest, alertify, hxzUI) {
  _.templateSettings = {
    interpolate: /\{\{(.+?)\}\}/g,
    evaluate: /<%([\s\S]+?)%>/g
  };

  // 封装Ajax请求
  var doGet = function (options, callback1, callback2) {
    $.ajax({
      type: 'get',
      url: options.url,
      timeout: 30000,
      success: function (o) {
        ajaxSuccessHandler(o);
        callback1(o);
      },
      error: function (err) {
        if (!callback2) {
          alertify.log("系统错误，请稍后再试");
          // 默认错误处理
        } else {
          callback2(err);
        }
      }
    });
  };

  var doPost = function (options, callback1, callback2) {
    $.ajax({
      type: 'post',
      url: options.url,
      data: options.data,
      timeout: 30000,
      success: function (o) {
        ajaxSuccessHandler(o);
        callback1(o);
      },
      error: function (err) {
        if (!callback2) {
          alertify.log("系统错误，请稍后再试");
          // 默认错误处理
        } else {
          callback2(err);
        }
      }
    });
  };

  /**
   * 收到返回的ajax请求数据后，进行的统一处理
   * @constructor
   */
  function ajaxSuccessHandler(o) {
    // session过期
    if (o.status == "2") {
      window.location.href = o.data;
    }
  }

  // 时间
  function MyDate(time) {
    this.time = time;
    this.dateObj = new Date(time);
    this.today = new Date();
  }

  MyDate.prototype.getWeek = function () {
    var w = ['日', '一', '二', '三', '四', '五', '六'];
    return '星期' + w[this.dateObj.getDay()];
  };

  MyDate.prototype.getDate = function () {
    /*后台时间为了格式统一,统一显示成年月日 不考虑省略年份的情况*/
    //if (this.today.getFullYear() === this.dateObj.getFullYear()) {
    //  return this.format('MM月dd日');
    //} else {
    //  return this.format('yyyy年MM月dd日');
    //}
    return this.format('yyyy-MM-dd');
  };

  MyDate.prototype.getTime = function () {
    return this.format('hh:mm');
  }

  MyDate.prototype.getDateTime = function () {
    /*后台时间为了格式统一,统一显示成年月日 不考虑省略年份的情况*/

    //if (this.today.getFullYear() === this.dateObj.getFullYear()) {
    //  return this.format('MM月dd日 hh:mm')
    //} else {
    //  return this.format('yyyy年MM月dd日 hh:mm');
    //}
    return this.format('yyyy-MM-dd hh:mm');
  };

  MyDate.prototype.getDateTimeWithSecond = function () {
    /*后台时间为了格式统一,统一显示成年月日 不考虑省略年份的情况*/

    //if (this.today.getFullYear() === this.dateObj.getFullYear()) {
    //  return this.format('MM月dd日 hh:mm')
    //} else {
    //  return this.format('yyyy年MM月dd日 hh:mm');
    //}
    return this.format('yyyy-MM-dd hh:mm:ss');
  };

  MyDate.prototype.format = function (format) {
    var d = this.dateObj;
    var o = {
      "M+": d.getMonth() + 1, //month
      "d+": d.getDate(), //day
      "h+": d.getHours(), //hour
      "m+": d.getMinutes(), //minute
      "s+": d.getSeconds(), //second
      "q+": Math.floor((d.getMonth() + 3) / 3), //quarter
      "S": d.getMilliseconds() //millisecond
    }

    if (/(y+)/.test(format)) {
      format = format.replace(RegExp.$1, (d.getFullYear() + "").substr(4 - RegExp.$1.length));
    }

    for (var k in o) {
      if (new RegExp("(" + k + ")").test(format)) {
        format = format.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
      }
    }
    return format;
  }

  var timeStamp2String = function (time) {
    var myDate = new MyDate(time);
    return myDate.getDateTime();
  };

  var getDate2String = function (time) {
    var myDate = new MyDate(time);
    return myDate.getDateTime();
  };

  var datetime = function (time) {
    var myDate = new MyDate(time);
    return myDate.getDateTime();
  };


  var date = function (time) {
    var myDate = new MyDate(time);
    return myDate.getDate();
  };

  var dateTimeWithSecond = function (time) {
    var myDate = new MyDate(time);
    return myDate.getDateTimeWithSecond();
  };

  function getUrlByfiterOption(url, filterOption) {
    if (filterOption && !(_.isEmpty(filterOption))) {
      /*开始根据option的类型拼写url*/
      url = url + "?";
      for (var key in filterOption) {
        if (filterOption[key] != undefined) {
          url = url + key + "=" + filterOption[key] + "&";
        }
      }
      url = url.substring(0, url.lastIndexOf("&"));
    }
    return url;
  }

  var getWechatUrl = function (page, data) {
    var url = "http://" + data.domain;
    switch (page) {
      case 'episodeList':
        url += "/wechat/activity/episode-list" + data.params;
        break;
      case 'episodeDetail':
        url += "/wechat/activity/episode-detail" + data.params;
        break;
      case 'hotelDetail':
        url += "/wechat/activity/hotel-detail" + data.params;
        break;
      case 'activityList':
        url += "/wechat/activity/list" + data.params;
        break;
      case 'center':
        url += "/wechat/center" + data.params;
        break;
      case 'hotelDetail':
        url += "/wechat/activity/hotel-detail" + data.params;
        break;
      case 'marketingDetail':
        url += "/wechat/marketing/start" + data.params;
        break;
    }
    return url;
  };

  function isNum(s) {
    if (s != null) {
      var r, re;
      re = /\d*/i; //\d表示数字,*表示匹配多个数字
      r = s.match(re);
      return (r == s) ? true : false;
    }
    return false;
  }

  function pageIndex(i, page) {
    return Number(i + 1) + Number((page - 1) * 10);
  }

  function activityStatus(status) {
    var s = ['未发布', '已发布', '已关闭'];
    return s[status];
  }

  function titleFilter(key, value) {
    /* 0是活动 1是旅游 2是教练 3雪票  4装备 5 冬令营*/
    var data = {
      actIntroduction: ['活动介绍', '费用说明', '产品介绍', '雪场介绍', '商品介绍', '详细介绍'],
      actHelp: ['活动须知', '行程介绍', '常见问题', '购票须知', '购买须知', '活动须知'],
      actStatement: ['免责声明', '注意事项', '免责声明', '使用说明', '注意事项', '注意事项']
    };
    return data[key][value];
  }

  function marketingType(type){
    var s = ['随机活动'];
    return s[type];
  }

  function episodeStatus(status) {
    var s = ['未发布', '有名额', '已满员', '已取消', '审核中', '已暂停'];
    return s[status];
  }


  var rewardType = function (data) {
    var s = ['无', '雪球', '礼物'];
    return s[data];
  };

  function orderStatus(status) {
    var s = ['未支付', '可使用', '退款中', '已退款', '已关闭', '已完成'];
    return s[status];
  }

  function streamStatus(status) {
    var s = ['', '收入', '退款', '结算'];
    return s[status];
  }

  function withdrawalStatus(status) {
    var s = ['处理中', '已转账', '已拒绝', '主动转账中(滑雪族)', '主动转账(滑雪族)'];
    return s[status];
  }

  function escapeHtml(string) {
    var entityMap = {
      "&": "&amp;",
      "<": "&lt;",
      ">": "&gt;",
      '"': '&quot;',
      "'": '&#39;',
      "/": '&#x2F;'
    };
    return String(string).replace(/[&<>"'\/]/g, function (s) {
      return entityMap[s];
    });
  }

  var activityOptionGroup = function (activity, episode, typeId, isManager) {
    var $activitySelector = $(activity);
    var $episodeSelector = $(episode);
    var params = '';
    if (typeId) params = "?typeId=" + typeId;
    var activityUrl = hxz.RestApi.activityOption;
    var episodeUrl = hxz.RestApi.episodeOption;
    if (isManager && isManager === 1) {
      activityUrl = hxz.RestApi.manageActivityOption;
      episodeUrl = hxz.RestApi.manageEpisodeOption;
    }

    // 获取产品
    hxz.doGet({url: activityUrl + params}, function (o) {
      o.data.unshift({"id": 0, "text": "全部"});
      $activitySelector.select2({
        language: "zh-CN",
        placeholder: "请选择产品",
        width: "350",
        data: o.data
      }).on("change", function (e) {
        $episodeSelector.empty();
        if (e.target.value) {
          // 获取子项目
          hxz.doGet({url: episodeUrl + "?activityId=" + e.target.value}, function (o) {
            o.data.unshift({"id": 0, "text": "全部"});
            $("#episode-form-group").show();
            $episodeSelector.select2({
              language: "zh-CN",
              placeholder: "请选择子项目",
              width: "350",
              data: o.data
            });
          });
        }
      });
    });
  };

  var hxz = {
    progressBar: hxzUI.progressBar,
    RestApi: hxzRest,
    valid: valid,
    overlay: null,
    // js时间转换
    datetime: datetime,
    rewardType: rewardType,
    escapeHtml: escapeHtml,
    date: date,
    dateTimeWithSecond: dateTimeWithSecond,
    timeStamp2String: timeStamp2String,
    getDate2String: getDate2String,
    pageIndex: pageIndex,
    isNum: isNum,
    doPost: doPost,
    doGet: doGet,
    activityOptionGroup: activityOptionGroup,
    getUrlByfiterOption: getUrlByfiterOption,
    getWechatUrl: getWechatUrl,
    titleFilter: titleFilter,
    getActivityStatus: activityStatus,
    episodeStatus: episodeStatus,
    orderStatus: orderStatus,
    streamStatus: streamStatus,
    marketingType: marketingType,
    withdrawalStatus: withdrawalStatus,
    // 截取字符串，结尾用“...”省略
    cutOff: function (str, length) {
      if (str.length <= length) {
        return str;
      }
      var nStr = str.substr(0, length);
      nStr += '...';
      return nStr;
    },
    // 错误处理
    errMsg: function (msg) {
      if (!/msie/.test(navigator.userAgent.toLowerCase())) {
      }
    }

  };
  return hxz;
});

Date.prototype.pattern = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1, //月份
    "d+": this.getDate(), //日
    "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
    "H+": this.getHours(), //小时
    "m+": this.getMinutes(), //分
    "s+": this.getSeconds(), //秒
    "q+": Math.floor((this.getMonth() + 3) / 3), //季度
    "S": this.getMilliseconds() //毫秒
  };
  var week = {
    "0": "/u65e5",
    "1": "/u4e00",
    "2": "/u4e8c",
    "3": "/u4e09",
    "4": "/u56db",
    "5": "/u4e94",
    "6": "/u516d"
  };
  if (/(y+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  if (/(E+)/.test(fmt)) {
    fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    }
  }
  return fmt;
};
